package com.hue.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hue.entity.Users;
import com.hue.service.UsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/*
    Shiro的Realm类：必须继承AuthorizingRealm
 */
public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private UsersService usersService;

    /*
        授权逻辑
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authenticationInfo = new SimpleAuthorizationInfo();
        //获取当前登录的用户
        Subject subject = SecurityUtils.getSubject();
        //查询当前登录的用户具有那些权限
        Users users = (Users) subject.getPrincipal();
        //给用户授予自己拥有的权限
        authenticationInfo.addStringPermission(users.getPerms());
        return authenticationInfo;
    }

    /*
        认证逻辑
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户输入的用户名和密码信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //查询用户
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", token.getUsername());
        Users users = usersService.getOne(wrapper);
        //用户不存在
        if (users == null) {
            //用户不存在返回null,shiro会抛出UnknownAccountException异常
            return null;
        }
        //验证密码是否正确,第一个参数为数据库中查询到的用户
        //第二个参数为数据库中的密码，shiro会自动判断用户输入的密码和数据库中的密码是否相同
        return new SimpleAuthenticationInfo(users, users.getPassword(), "");
    }
}
